package hu.plusone.eregister.controller;

import hu.plusone.eregister.form.ChildForm;
import hu.plusone.eregister.model.Child;
import hu.plusone.eregister.model.Nursery;
import hu.plusone.eregister.service.ChildService;
import hu.plusone.eregister.service.NurseryService;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/child")
public class ChildController {

    private static final Logger logger = LoggerFactory.getLogger(ChildController.class);
    private static final String PAGE_LIST = "child/list";
    private static final String PAGE_EDIT = "child/edit";
    @Autowired
    private ChildService service;
    @Autowired
    private NurseryService nurseryService;

    @RequestMapping("/list")
    public String listAll(Model model) {
        model.addAttribute("modelList", service.getAll());
        return PAGE_LIST;
    }

    @RequestMapping("/delete")
    public String delete(Model model, @RequestParam(required = true) long id) {
        service.delete(id);
        return listAll(model);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String editForm(Model model, @RequestParam(required = false) Long id) {

        Child entity;
        if (id == null) {
            entity = new Child();
        } else {
            entity = service.get(id);
        }

        ChildForm childForm = new ChildForm();
        childForm.setChild(entity);
        childForm.setNurseries(findNurseries(entity.getId()));

        model.addAttribute("childForm", childForm);
        model.addAttribute("all_nurseries", nurseryService.getAll());

        return PAGE_EDIT;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(Model model, @ModelAttribute("entity") ChildForm form) {
        Child child = form.getChild();
        child.setNurseries(form.getNurseries());
        service.save(child);
        return listAll(model);
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
        binder.registerCustomEditor(Collection.class, new CustomCollectionEditor(Collection.class) {
            @Override
            protected Object convertElement(Object element) {
                Assert.notNull(element);

                Long id = null;
                if (element instanceof Long) {
                    id = (Long) element;
                } else if (element instanceof Nursery) {
                    return element;
                } else if (element instanceof String) {
                    id = Long.parseLong(element.toString());
                }
                return id == null ? null : nurseryService.get(id);
            }
        });
    }

    private Collection<Nursery> findNurseries(Long childId) {
        Collection<Nursery> nurseries = nurseryService.findAllByChildId(childId);
        logger.debug("findNurseries: {}", childId);
        for (Nursery nursery : nurseries) {
            logger.debug("n: {}", nursery);
        }
        return nurseryService.findAllByChildId(childId);
    }
}
